<script setup>
import { ref, onMounted } from 'vue'
import { getFileTypes, preUpload, confirmUpload } from '@/api/fileApi'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['upload-success', 'close-dialog'])

// 重置表单状态
const reset = () => {
  selectedFile.value = null
  previewData.value = null
  selectedTypeId.value = null
  chunkType.value = 1
}

defineExpose({
  reset,
})

// 文件类型列表
const fileTypes = ref([])
// 选中的文件对象
const selectedFile = ref(null)
// 预上传返回的预览数据
const previewData = ref(null)
// 选中的文件类型ID
const selectedTypeId = ref(null)
// 切分类型 (0:不切分,1:固定长度切分,2:标题增强切分)
const chunkType = ref(1)

// 获取文件类型列表
const loadFileTypes = async () => {
  try {
    const response = await getFileTypes()
    if (response?.data?.data?.typeSummaries) {
      fileTypes.value = response.data.data.typeSummaries.map((item) => ({
        id: item.typeId,
        name: item.name,
      }))
    } else {
      throw new Error('接口返回数据格式不正确')
    }
  } catch (error) {
    console.error('获取文件类型失败:', error)
    ElMessage.error('文件类型加载失败，请点击重试按钮')
  }
}

// 组件初始化时加载文件类型
onMounted(() => {
  loadFileTypes()
})

// 处理文件选择事件
const handleFileSelect = async (event) => {
  if (event.target.files && event.target.files.length > 0) {
    if (!selectedTypeId.value) {
      ElMessage.warning('请先选择文件类型')
      return
    }
    selectedFile.value = event.target.files[0]
    await processFileUpload()
  }
}

const handleFileDrop = async (event) => {
  event.preventDefault()
  if (event.dataTransfer.files && event.dataTransfer.files.length > 0) {
    // 检查是否已有选中文件
    if (selectedFile.value) {
      ElMessage.warning('已有文件正在处理，请等待完成')
      return
    }
    if (!selectedTypeId.value) {
      ElMessage.warning('请先选择文件类型')
      return
    }
    selectedFile.value = event.dataTransfer.files[0]
    await processFileUpload()
  } else {
    ElMessage.warning('请拖放有效的文件')
  }
}

const processFileUpload = async () => {
  const formData = new FormData()
  formData.append('file', selectedFile.value)
  formData.append('type', selectedTypeId.value)
  formData.append('chunkType', chunkType.value)

  try {
    // 调用预上传接口
    const response = await preUpload(formData)
    previewData.value = response.data.data
    emit('upload-success', {
      chunks: response.data.data.chunks,
      filename: response.data.data.filename,
      typeId: selectedTypeId.value,
      chunkType: chunkType.value,
    })
  } catch (error) {
    console.error('预上传处理失败:', error)
    ElMessage.error('文件预处理失败：' + error.message)
  }
}

// 确认提交处理
const handleConfirm = async () => {
  if (!previewData.value) {
    ElMessage.warning('请先完成预上传')
    return
  }

  try {
    await confirmUpload({
      ...previewData.value,
      file: selectedFile.value,
    })
    ElMessage.success('文件上传成功!')
    // 重置状态
    previewData.value = null
    selectedFile.value = null
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('文件提交失败：' + error.message)
  }
}
</script>

<template>
  <div class="upload-container" ref="uploadContainer">
    <!-- 文件类型选择 -->
    <div class="form-group">
      <label>文件类型：<span style="color: red">*</span></label>
      <div class="type-select-container">
        <el-select
          v-model="selectedTypeId"
          placeholder="请选择文件类型"
          @change="loadFileTypes"
          :rules="[{ required: true, message: '请选择文件类型', trigger: 'change' }]"
        >
          <el-option v-for="type in fileTypes" :key="type.id" :label="type.name" :value="type.id" />
        </el-select>
        <el-button v-if="!fileTypes.length" type="primary" @click="loadFileTypes" class="retry-btn">
          重试
        </el-button>
      </div>
    </div>

    <!-- 切分类型选择 -->
    <div class="form-group">
      <label>切分方式：</label>
      <el-radio-group
        v-model="chunkType"
        @change="
          () => {
            if (!selectedFile) {
              ElMessage.warning('请先选择文件')
              return
            }
            processFileUpload()
          }
        "
      >
        <!-- <el-radio :label="0">不切分</el-radio> -->
        <el-radio :label="1">固定长度切分</el-radio>
        <el-radio :label="2">标题增强切分</el-radio>
        <el-radio :label="3">语义分割</el-radio>
      </el-radio-group>
    </div>

    <!-- 文件拖放区域 -->
    <div
      class="file-drop-zone"
      @dragover.prevent
      @drop="handleFileDrop"
      @click="$refs.fileInput.click()"
    >
      <input
        ref="fileInput"
        type="file"
        @change="handleFileSelect"
        accept=".docx,.xlsx,.doc,.pdf"
      />
      <p>点击选择文件</p>
    </div>

    <!-- 分割预览组件 -->
    <ChunkPreview v-if="previewData" :chunks="previewData.chunks" @confirm="handleConfirm" />
  </div>
</template>

<style scoped>
.upload-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-drop-zone {
  border: 2px dashed #4dabf7;
  padding: 3rem 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.file-drop-zone:hover {
  border-color: #228be6;
  background-color: #e7f5ff;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.type-select-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.retry-btn {
  margin-left: 10px;
}

input[type='file'] {
  display: none;
}
</style>
